CFLAGS ?= -Wall -pipe -g -ggdb -DONLINE_JUDGE -DNDEBUG
CXXFLAGS ?= $(CFLAGS)
ODIR := .objs
TESTIGO := $(ODIR)/.keep_me
PROGS := $(patsubst ej%.cpp, ej%, $(wildcard ej?.cpp)) g1

.PHONY: all clean
all: $(PROGS)
clean:
	rm -rf $(PROGS) $(ODIR)

$(TESTIGO):
	mkdir $(ODIR)
	touch $(TESTIGO)

define EJ_template
$(1): $(TESTIGO) $(ODIR)/$(1).o # $(ODIR)/main.o
	$(CXX) $(CXXFLAGS) $(ODIR)/$(1).o -o $$@

$(ODIR)/$(1).d: $(TESTIGO) $(1).cpp
	set -e; rm -f $@; \
	$(CXX) $(CXXFLAGS) -MM $(1).cpp > $$@.$$$$$$$$; \
	sed 's,$(1)\.o[ :]*,$(ODIR)/$(1).o $$@ : ,g' < $$@.$$$$$$$$ > $$@; \
	rm -f $$@.$$$$$$$$
endef

$(ODIR)/%.o: %.cpp
	$(CXX) $(CXXFLAGS) -c $< -o $@

$(foreach prog,$(PROGS),$(eval $(call EJ_template,$(prog))))

include $(addsuffix .d, $(addprefix $(ODIR)/,$(PROGS)))
